<template>
	<view class="box">
		<!-- #ifdef H5 || MP-WEIXIN -->
		<view class="">
			<u-navbar title="选择聊天" :fixed="true" :placeholder="true" :safeAreaInsetTop="true" :autoBack="false"
				leftIconColor="#666" titleStyle="color:#333" bgColor="transparent" @leftClick="leftClick"></u-navbar>
			<image class="indexbg"
				src="https://images.fudiemall.com/storage/default/20250411/BG77ff634c5c493fbb0cb752c7b44d86c703900c11.png"
				mode="aspectFill"></image>
		</view>
		<!-- #endif -->
		<!-- #ifdef MP-ALIPAY -->
		<NavTitle title="选择聊天"
			bgimg='https://images.fudiemall.com/storage/default/20250411/BG77ff634c5c493fbb0cb752c7b44d86c703900c11.png'
			:backgroundColor='backgroundColor'></NavTitle>
		<!-- #endif -->

		<view class="main">
			<!-- <checkbox-group @change="checkboxChangeAll">
				<view class="item" v-for="item in merberlist" :key="item.hx_group_id">
					<image :src="item.avatar" mode="aspectFill"></image>
					<text>{{item.name}}</text>
						<checkbox  borderColor="#333" activeBorderColor="#FFC300" class="checkitem"
							activeBackgroundColor="#FFC300" backgroundColor="#f2f2f2" :checked="false"
							:value="item.hx_group_id.toString()"></checkbox>
				</view>
			</checkbox-group> -->
			<u-checkbox-group iconPlacement="right" placement="column" @change="checkboxChangeAll">
				<view class="item" v-for="item in merberlist" :key="item.hx_group_id">
					<image :src="item.avatar" mode="aspectFill"></image>
					<text>{{item.name}}</text>
					<u-checkbox v-if="isshow" shape='circle' class="checkitem" size='15' :checked='false' activeColor='#FFC300' :name="item.hx_group_id.toString()"></u-checkbox>
						
				</view>
			</u-checkbox-group>
		</view>
		<noDatas :xxxList="merberlist" :showMore="false"></noDatas>

		<view class="empty3">

		</view>
		<view class="empty3">

		</view>

		<view class="btn" @click="right">
			{{righttxt}}
		</view>

		<view style="width: 750rpx;height: 88rpx;">

		</view>
	</view>
</template>

<script>
	import {
		groupDetails,
		memberGroupList,
		setAdministrator
	} from "../../api/hx.js"
	import {
		myuser
	} from "../../api/user.js"
	export default {
		data() {
			return {
				selectedIds: [],
				isshow: false,
				righttxt: "点击选择",
				word: "",
				merberlist: [],
				groupid: "",
				tit: "",
				groupinfo: "",
				is_admin: "",
				user: {},

			}
		},
		onLoad() {
			this.getuser()
			this.getlist()

		},
		onShow() {


		},
		methods: {
			set() {

				let forwardingitem = uni.getStorageSync("forwardingitem")
				if (forwardingitem.msgType == 'txt') {
					if (this.selectedIds.length === 0) {
						uni.$u.toast("请选择至少一个群组进行转发");
						return;
					}

					// 创建Promise数组
					const promises = this.selectedIds.map(groupId => {
						// 查找当前群组的详细信息
						const groupInfo = this.merberlist.find(member => member.hx_group_id === groupId);
						if (!groupInfo) {
							return Promise.reject(new Error(`未找到群组信息，群组ID：${groupId}`));
						}

						// 创建消息选项
						const option = {
							type: forwardingitem.msgType,
							msg: forwardingitem.content,
							to: groupId,
							chatType: "groupChat",
							ext: {
								nickname: this.user.nickname,
								head_img: this.user.avatar,
								groupname: groupInfo.name,
								groupheadimg: groupInfo.avatar,

							}
						};

						// 创建消息
						const msg = uni.WebIM.message.create(option);

						// 发送消息并返回Promise
						return uni.WebIM.conn.send(msg)
							.then(res => ({
								groupId,
								success: true,
								result: res
							}))
							.catch(e => ({
								groupId,
								success: false,
								error: e
							}));
					});

					// 处理所有Promise的结果
					Promise.all(promises)
						.then(results => {
							console.log("所有消息发送完成");
							const successCount = results.filter(item => item.success).length;
							const failedCount = results.length - successCount;

							console.log(`成功发送到 ${successCount} 个群组，失败 ${failedCount} 个`);

							// 处理失败结果
							const failedResults = results.filter(item => !item.success);
							failedResults.forEach(failed => {
								const error = failed.error;
								console.log(error, '错误')
								console.log(`群组 ${failed.groupId} 发送失败，错误：${error}`);
								// 根据错误类型显示不同的提示
								if (error.type === 506) {
									uni.$u.toast("全体禁言中");
								} else if (error.type === 507) {
									uni.$u.toast("你已被禁言，请联系管理员");
								} else {
									uni.$u.toast(`发送失败，错误代码：${error.type}`);
								}
							});

							if (failedCount === 0) {
								setTimeout(() => {
									uni.navigateBack()
								}, 1000)
								uni.$u.toast("消息已成功发送到所有选中的群组");
							}
						})
						.catch(e => {
							console.log("发送消息失败:", e);
							uni.$u.toast("消息发送失败，请检查网络或联系管理员");
						});

				} else if (forwardingitem.msgType == 'img') {
					if (this.selectedIds.length === 0) {
						uni.$u.toast("请选择至少一个群组进行转发");
						return;
					}

					// 创建Promise数组
					const promises = this.selectedIds.map(groupId => {
						// 查找当前群组的详细信息
						const groupInfo = this.merberlist.find(member => member.hx_group_id === groupId);
						if (!groupInfo) {
							return Promise.reject(new Error(`未找到群组信息，群组ID：${groupId}`));
						}

						// 创建消息选项
						const option = {
							type: forwardingitem.msgType,
							url: forwardingitem.url,
							to: groupId,
							chatType: "groupChat",
							width: forwardingitem.width,
							height: forwardingitem.height,
							ext: {
								nickname: this.user.nickname,
								head_img: this.user.avatar,
								groupname: groupInfo.name,
								groupheadimg: groupInfo.avatar,

							}
						};
						console.log(option, "查看发送内容")
						// 创建消息
						const msg = uni.WebIM.message.create(option);

						// 发送消息并返回Promise
						return uni.WebIM.conn.send(msg)
							.then(res => ({
								groupId,
								success: true,
								result: res
							}))
							.catch(e => ({
								groupId,
								success: false,
								error: e
							}));
					});

					// 处理所有Promise的结果
					Promise.all(promises)
						.then(results => {
							console.log("所有消息发送完成");
							const successCount = results.filter(item => item.success).length;
							const failedCount = results.length - successCount;

							console.log(`成功发送到 ${successCount} 个群组，失败 ${failedCount} 个`);

							// 处理失败结果
							const failedResults = results.filter(item => !item.success);
							failedResults.forEach(failed => {
								const error = failed.error;
								console.log(error, '错误')
								console.log(`群组 ${failed.groupId} 发送失败，错误：${error}`);
								// 根据错误类型显示不同的提示
								if (error.type === 506) {
									uni.$u.toast("全体禁言中");
								} else if (error.type === 507) {
									uni.$u.toast("你已被禁言，请联系管理员");
								} else {
									uni.$u.toast(`发送失败，错误代码：${error.type}`);
								}
							});

							if (failedCount === 0) {
								setTimeout(() => {
									uni.navigateBack()
								}, 1000)
								uni.$u.toast("消息已成功发送到所有选中的群组");
							}
						})
						.catch(e => {
							console.log("发送消息失败:", e);
							uni.$u.toast("消息发送失败，请检查网络或联系管理员");
						});

				} else if (forwardingitem.msgType == 'video') {
					if (this.selectedIds.length === 0) {
						uni.$u.toast("请选择至少一个群组进行转发");
						return;
					}

					// 创建Promise数组
					const promises = this.selectedIds.map(groupId => {
						// 查找当前群组的详细信息
						const groupInfo = this.merberlist.find(member => member.hx_group_id === groupId);
						if (!groupInfo) {
							return Promise.reject(new Error(`未找到群组信息，群组ID：${groupId}`));
						}

						// 创建消息选项
						const option = {
							type: forwardingitem.msgType,
							filename: "filename",
							to: groupId,
							chatType: "groupChat",
							body: {
								//文件 URL。
								url: forwardingitem.url,
								//文件类型。
								type: "video",
								//文件名称。
								filename: "filename",
							},
							ext: {
								video_thumb: forwardingitem.video_thumb ? forwardingitem.video_thumb :
									forwardingitem.thumb,
								nickname: this.user.nickname,
								head_img: this.user.avatar,
								groupname: groupInfo.name,
								groupheadimg: groupInfo.avatar,

							}
						};
						// var option = {
						// 											// 消息类型。
						// 											type: "video",
						// 											// 会话类型：单聊、群聊和聊天室分别为 `singleChat`、`groupChat` 和 `chatRoom`。
						// 											chatType: "groupChat",
						// 											// 文件名。
						// 											filename: "filename",
						// 											// 消息接收方：单聊为对方用户 ID，群聊和聊天室分别为群组 ID 和聊天室 ID。
						// 											to: me.groupid,
						// 											body: {
						// 												//文件 URL。
						// 												url: dataObj.uri + "/" + dataObj.entities[0]
						// 													.uuid,
						// 												//文件类型。
						// 												type: "video",
						// 												//文件名称。
						// 												filename: "filename",
						// 											},
						// 											ext: {
						// 												nickname: me.user.nickname,
						// 												head_img: me.user.avatar,
						// 												groupname: me.groupinfo.name,
						// 												groupheadimg: me.groupinfo.avatar,
						// 												is_shield: me.groupinfo.group_user_one.is_shield
						// 											},
						// 										}
						// 创建消息
						console.log(option, "视频消息")
						const msg = uni.WebIM.message.create(option);

						// 发送消息并返回Promise
						return uni.WebIM.conn.send(msg)
							.then(res => ({
								groupId,
								success: true,
								result: res,
							}))
							.catch(e => ({
								groupId,
								success: false,
								error: e
							}));
					});

					// 处理所有Promise的结果
					Promise.all(promises)
						.then(results => {
							console.log(results, "查看消息发送内容")
							console.log("所有消息发送完成");
							const successCount = results.filter(item => item.success).length;
							const failedCount = results.length - successCount;

							console.log(`成功发送到 ${successCount} 个群组，失败 ${failedCount} 个`);

							// 处理失败结果
							const failedResults = results.filter(item => !item.success);
							failedResults.forEach(failed => {
								const error = failed.error;
								console.log(error, '错误')
								console.log(`群组 ${failed.groupId} 发送失败，错误：${error}`);
								// 根据错误类型显示不同的提示
								if (error.type === 506) {
									uni.$u.toast("全体禁言中");
								} else if (error.type === 507) {
									uni.$u.toast("你已被禁言，请联系管理员");
								} else {
									uni.$u.toast(`发送失败，错误代码：${error.type}`);
								}
							});

							if (failedCount === 0) {
								setTimeout(() => {
									uni.navigateBack()
								}, 1000)
								uni.$u.toast("消息已成功发送到所有选中的群组");
							}
						})
						.catch(e => {
							console.log("发送消息失败:", e);
							uni.$u.toast("消息发送失败，请检查网络或联系管理员");
						});

				}
			},
			getuser() {
				myuser().then(res => {
					this.user = res.data
				})
			},
			gomore(item) {
				if (this.is_admin != 0 && this.user.id != item.member_id) {

					uni.setStorageSync("groupitem", item)
					uni.navigateTo({
						url: "/pagesMy/chat/more?id=" + this.groupid
					})

				}
			},
			leftClick() {
				//获取页面栈的长度
				const canNavBack = getCurrentPages()
				console.log(canNavBack.length);
				// 判断是否刷新了浏览器，刷新了浏览器，页面栈只有当前一个
				if (canNavBack.length > 1) {
					uni.navigateBack({
						delta: 1
					})
				} else {
					uni.switchTab({
						url: '/pages/index/cloudCatIndex'
					})
				}
			},
			sub() {
				this.page = 1,
					this.getlist()
			},
			groupdetail() {
				groupDetails({
					hx_group_id: this.groupid
				}).then(res => {
					if (res.code == 1) {
						this.groupinfo = res.data
						this.is_admin = res.data.group_user_one.is_admin
						this.tit = `${this.groupinfo.name}(${this.groupinfo.member_number}人)`
						// console.log("群详情", res)
					} else {
						uni.$u.toast(res.msg)
					}

				})
			},
			getlist() {
				memberGroupList({


				}).then(res => {
					if (res.code == 1) {
						this.merberlist = res.data

					}
				})
			},

			right() {
				this.isshow = true
				this.righttxt = "点击转发"
				if (this.selectedIds.length != 0) {
					this.set()



				}
			},
			checkboxChangeAll(e) {
				console.log(e);
				this.selectedIds = e;
				// this.selectedIds = e.detail.value;
				console.log(this.selectedIds)
			},
		},

	}
</script>
<style>
	page {
		background-color: #f7f7f7;
	}
</style>
<style lang="scss">
	.box {
		width: 750rpx;

	}

	.btn {
		width: 696rpx;
		height: 80rpx;
		background: linear-gradient(270deg, #FA2222 2%, #FFC400 98%);
		border-radius: 190rpx 190rpx 190rpx 190rpx;
		font-weight: 500;
		font-size: 36rpx;
		color: #FFFFFF;
		text-align: center;
		line-height: 80rpx;
		position: fixed;
		bottom: 50rpx;
		left: 50%;
		transform: translateX(-50%);
	}

	/deep/.u-navbar__content {
		background: transparent;
	}

	.indexbg {
		position: absolute;
		top: 0;
		left: 0;
		width: 750rpx;
		height: 460rpx;

	}

	/deep/ .u-navbar__content__right__text {
		color: #FF1616;
	}

	.wrap_top {
		width: 750rpx;
	}

	.search {
		width: 690rpx;
		height: 72rpx;
		background: #E0DDDA;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		margin: 0 auto;
		position: relative;

		>image {
			width: 32rpx;
			height: 30rpx;
			position: absolute;
			top: 22rpx;
			left: 34rpx;

		}

		>input {
			width: 620rpx;
			padding-left: 70rpx;
			height: 72rpx;
			font-weight: 400;
			font-size: 28rpx;
			color: rgba(255, 255, 255, 0.8);
		}
	}

	.main {
		width: 750rpx;
		z-index: 999;
	}

	.item {
		width: 690rpx;
		margin: 0 auto;
		margin-top: 24rpx;
		display: flex;
		align-items: center;
		position: relative;
		z-index: 15;

		>image {
			width: 84rpx;
			height: 84rpx;
			border-radius: 50%;
		}

		>text {
			font-weight: 400;
			font-size: 30rpx;
			color: #333;
			margin-left: 15rpx;
			max-width: 300rpx;
			white-space: nowrap;
			/* 防止文本换行 */
			overflow: hidden;
			/* 隐藏溢出的文本 */
			text-overflow: ellipsis;
			/* 当文本溢出时显示省略号 */
		}

		.tag {
			padding: 5rpx 10rpx 5rpx 10rpx;
			background: #FFC300;
			border-radius: 4rpx 4rpx 4rpx 4rpx;
			opacity: 0.5;
			font-size: 20rpx;
			color: #fff;
			text-align: center;
			margin-left: 20rpx;
		}

		/deep/.uni-checkbox-input {
			width: 30rpx;
			height: 30rpx;
			position: absolute;
			right: 40rpx;
			border-radius: 50%;
		}
		/deep/.u-checkbox {
			width: 30rpx;
			height: 30rpx;
			position: absolute;
			right: 40rpx;
			border-radius: 50%;
		}
	}
</style>